package com.aji.alluser.service.impl;


import com.aji.alluser.domain.LoginUser;
import com.aji.alluser.domain.User;
import com.aji.alluser.mapper.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        User user = loginMapper.getByUserName(username);
        System.out.println("user:"+user);

        // 2. 查询用户角色
        List<String> roles = loginMapper.selectRolesByUserId(user.getId());
        System.out.println(roles);

        // 3. 转换为 GrantedAuthority（必须加 ROLE_ 前缀）
        List<GrantedAuthority> authorities = roles.stream()
                .map(role -> role.startsWith("ROLE_") ? role : "ROLE_" + role.toUpperCase())
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        // 4. 返回 LoginUser
        return new LoginUser(user, authorities);
    }
}
